import urllib.request
import os
import ssl
import hashlib
import base64
import sys
#import json
ssl._create_default_https_context = ssl._create_unverified_context
PrivateKey = "6imwjBlIt1A1QvExFpwgRydq8O1ZafcvjzQspXNboUN5lvmlupiioapSzlWdGv3y"
url = 'https://api-cn-sh2.iot.ucloud.cn'
headers = {
    'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
}
'''
values = {
    "Action": "GetUIoTCoreProductInfo",
    "ProductSN": "fsubp4njg1571vy1",
    "ProjectId": "org-eabywn",
    "PublicKey": "oMkmqMNe91mB5HfjWVLejRb21qmv9PzcwD80ZVNG",
    "Region": "cn-sh2",
    "Signature": ""
}
'''
if len(sys.argv) <= 1:
    print ("parm err")
    sys.exit(1)
if sys.argv[1] == '':
    print ("parm err")
    sys.exit(1)
print(sys.argv[1])
msg = sys.argv[1]
message = str(base64.b64encode(msg.encode("utf-8")), "utf-8")
values = {
    "Action": "PublishUIoTCoreMQTTMessage",
    "ProductSN": "fsubp4njg1571vy1",
    "TopicFullName":"/fsubp4njg1571vy1/c8478cdd37cd/set",
    "MessageContent":message,
    "Qos":1,
    "ProjectId": "org-eabywn",
    "PublicKey": "oMkmqMNe91mB5HfjWVLejRb21qmv9PzcwD80ZVNG",
    "Region": "cn-sh2",
}

sig_s = ""

for i in sorted(values):
    sig_s = sig_s+i+str(values[str(i)])

sig_s = sig_s+PrivateKey
p=hashlib.sha1()
p.update(sig_s.encode('utf-8'))
Signature = p.hexdigest()
values["Signature"] = Signature

data = urllib.parse.urlencode(values).encode('utf-8')

request = urllib.request.Request(url, data, headers)

html = urllib.request.urlopen(request).read().decode('utf-8')

print(html)



